import store from './../store'

//获取用户token，如果缓存有，直接返回，如果没有，就先微信登陆，然后服务器登陆，最后返回token
function userToken() {
	var token = uni.getStorageSync('userToken');
	if (!token) {
		uni.showToast({
			title: '请先登录!',
			icon: 'none',
			duration: 3000,
			success: function(res) {
				setTimeout(() => {
					uni.reLaunch({
						url: '../login/index'
					})
				}, 1000)
			}
		})
	}
}

function isLogin() {
	var token = uni.getStorageSync('userToken');
	if (token) {
		return true;
	}
	return false;
}

function toLogin() {
	debounce(() => {
		uni.showToast({
			title: '请先登录!',
			icon: 'none',
			duration: 2000,
			success: function(res) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
			}
		})
	}, 500)()

}

//把obj对象里的值覆盖到newobj里面
function deepCopy(newobj, obj) {
	if (typeof obj != 'object') {
		return obj
	}
	for (var attr in obj) {
		var a = {}
		if (newobj[attr]) {
			a = newobj[attr]
		}
		newobj[attr] = deepCopy(a, obj[attr])
	}
	return newobj
}

//当出错的时候，显示错误信息，并且跳转 弃用
/* function errorToBack(msg = '出错了，请重试',delta=1){
  uni.showToast({
    title: msg,
    icon: 'none',
    duration: 2000,
  });
  if(delta > 0){
    setTimeout(function () {
      uni.navigateBack({
        delta: delta
      })
    }, 1000);
  }
} */
//操作成功后，的提示信息
function successToShow(msg = '保存成功', callback = function() {}) {
	uni.showToast({
		title: msg,
		icon: 'success',
		duration: 1000
	})
	setTimeout(function() {
		callback()
	}, 1000)
}

//操作失败的提示信息
function errorToShow(msg = '操作失败', callback = function() {}, timeout = 1500) {
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: 1500
	})
	setTimeout(function() {
		callback()
	}, timeout)
}

//加载显示
function loadToShow(msg = '加载中') {
	uni.showToast({
		title: msg,
		icon: 'loading'
	})
}

//加载隐藏
function loadToHide() {
	uni.hideToast()
}

// 提示框
function modelShow(
	title = '提示',
	content = '确认执行此操作吗?',
	callback = () => {},
	showCancel = true,
	cancelText = '取消',
	confirmText = '确定'
) {
	uni.showModal({
		title: title,
		content: content,
		showCancel: showCancel,
		cancelText: cancelText,
		confirmText: confirmText,
		cancelText: cancelText,
		success: function(res) {
			if (res.confirm) {
				// 用户点击确定操作
				setTimeout(() => {
					callback()
				}, 500)
			} else if (res.cancel) {
				// 用户取消操作
			}
		}
	})
}

//时间戳转时间格式
function timeToDate(date, flag = false) {
	var date = new Date(date * 1000) //如果date为13位不需要乘1000
	var Y = date.getFullYear() + '-'
	var M =
		(date.getMonth() + 1 < 10 ?
			'0' + (date.getMonth() + 1) :
			date.getMonth() + 1) + '-'
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
	var m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
	var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
	if (flag) {
		return Y + M + D
	} else {
		return Y + M + D + h + m + s
	}
}
// 获取
function getmyDate(date, flag ) {
	var date = new Date(date) //如果date为13位不需要乘1000
	var Y = date.getFullYear() + '-'
	var M =
		(date.getMonth() + 1 < 10 ?
			'0' + (date.getMonth() + 1) :
			date.getMonth() + 1) + '-'
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
	var m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) 
	var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
	if (flag == 1) {
		return M + D
	} else {
		return h + m
	}
}

function time2date(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second)
	// 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2)
	// 小时
	time.hour = PrefixInteger(Math.floor((second / 3600) % 24), 2)
	// 分钟
	time.minute = PrefixInteger(Math.floor((second / 60) % 60), 2)
	// 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2)

	var newtime = ''
	if (time.day > 0) {
		newtime =
			time.day +
			'天' +
			time.hour +
			'小时' +
			time.minute +
			'分' +
			time.second +
			'秒'
	} else {
		if (time.hour != 0) {
			newtime = time.hour + '小时' + time.minute + '分' + time.second + '秒'
		} else {
			newtime = time.minute + '分' + time.second + '秒'
		}
	}
	return newtime
}

function timeToDateObj(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second)
	// 天数
	time.day = Math.floor(second / 3600 / 24)
	// 小时
	time.hour = Math.floor((second / 3600) % 24)
	// 分钟
	time.minute = Math.floor((second / 60) % 60)
	// 秒
	time.second = Math.floor(second % 60)

	return time

}

//货币格式化
function formatMoney(number, places, symbol, thousand, decimal) {
	number = number || 0
	places = !isNaN((places = Math.abs(places))) ? places : 2
	symbol = symbol !== undefined ? symbol : '￥'
	thousand = thousand || ','
	decimal = decimal || '.'
	var negative = number < 0 ? '-' : '',
		i = parseInt((number = Math.abs(+number || 0).toFixed(places)), 10) + '',
		j = (j = i.length) > 3 ? j % 3 : 0
	return (
		symbol +
		negative +
		(j ? i.substr(0, j) + thousand : '') +
		i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) +
		(places ?
			decimal +
			Math.abs(number - i)
			.toFixed(places)
			.slice(2) :
			'')
	)
}



// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second / 1000) // 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2) // 小时
	time.hour = PrefixInteger(Math.floor((second / 3600) % 24), 2) // 分钟
	time.minute = PrefixInteger(Math.floor((second / 60) % 60), 2) // 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2)
	return time
}

//不足位数前面补0
function PrefixInteger(num, length) {
	return (Array(length).join('0') + num).slice(-length)
}

//验证是否是手机号
function isPhoneNumber(str) {
	var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
	if (!myreg.test(str)) {
		return false
	} else {
		return true
	}
}

//是否是身份证
function isIdentity(identity) {
	var myreg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
	if (!myreg.test(identity)) {
		return false
	} else {
		return true
	}
}

/**
 *
 * 对象参数转为url参数
 *
 */
function builderUrlParams(url, data) {
	if (typeof url == 'undefined' || url == null || url == '') {
		return ''
	}
	if (typeof data == 'undefined' || data == null || typeof data != 'object') {
		return ''
	}
	url += url.indexOf('?') != -1 ? '' : '?'
	for (var k in data) {
		url += (url.indexOf('=') != -1 ? '&' : '') + k + '=' + encodeURI(data[k])
	}
	return url
}

/**
 * 使用循环的方式判断一个元素是否存在于一个数组中
 * @param {Object} arr 数组
 * @param {Object} value 元素值
 */
function isInArray(arr, value) {
	for (var i = 0; i < arr.length; i++) {
		if (value === arr[i]) {
			return true
		}
	}
	return false
}
/**
 * 统一跳转
 */
function navigateTo(url) {
	uni.navigateTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	})
}

/**
 *  关闭当前页面并跳转
 */
function redirectTo(url) {
	uni.redirectTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	})
}

/**
 * 获取url参数
 *
 * @param {*} name
 * @param {*} [url=window.location.serach]
 * @returns
 */
function getQueryString(name, url) {
	var url = url || window.location.href
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		return r[2]
	}
	return null
}

/**
 *
 *  判断是否在微信浏览器 true是
 */
function isWeiXinBrowser() {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	// #endif

	return false
}

/**
 * 金额相加
 * @param {Object} value1
 * @param {Object} value2
 */
function moneySum(value1, value2) {
	return (parseFloat(value1) + parseFloat(value2)).toFixed(2);
}
/**
 * 金额相减
 * @param {Object} value1
 * @param {Object} value2
 */
function moneySub(value1, value2) {
	let res = (parseFloat(value1) - parseFloat(value2)).toFixed(2);
	return res > 0 ? res : 0;
}


/**
 * 分享URL解压缩
 * @param {Object} url
 */
function shareParameterEncode(url) {
	let urlArray = url.split('-');
	let newUrl = 'type=' + urlArray[0] + '&invite=' + urlArray[1] + '&id=' + urlArray[2] + '&team_id=' + urlArray[3] +
		'&id_type=' + urlArray[4] + '&page_code=' + urlArray[5] + '&group_id=' + urlArray[6];
	return newUrl;
}


/**
 * 分享URL压缩
 * @param {Object} url
 */
function shareParameterDecode(url) {
	var urlArray = url.split('&');
	var allParameter = {
		'type': '',
		'invite': '',
		'id': '',
		'team_id': '',
		'id_type': '',
		'page_code': '',
		'group_id': '',
	};
	for (var i = 0; i < urlArray.length; i++) {
		var parameter = urlArray[i].split('=');
		allParameter[parameter[0]] = parameter[1];
	}
	var newUrl = allParameter.type + '-' + allParameter.invite + '-' + allParameter.id + '-' + allParameter.team_id +
		'-' +
		allParameter.id_type + '-' + allParameter.page_code + '-' + allParameter.group_id;
	return newUrl;
}

function formatDate(date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + '';
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
		}
	}
	return fmt;
}

function padLeftZero(str) {
	return ('00' + str).substr(str.length);
}

function str2Date(dateStr, separator) {
	if (!separator) {
		separator = "-";
	}
	let dateArr = dateStr.split(separator);
	let year = parseInt(dateArr[0]);
	let month;
	//处理月份为04这样的情况
	if (dateArr[1].indexOf("0") == 0) {
		month = parseInt(dateArr[1].substring(1));
	} else {
		month = parseInt(dateArr[1]);
	}
	let day = parseInt(dateArr[2]);
	let date = new Date(year, month - 1, day);
	return date;
}

const isBlankString = val => {
	var re = /^[ ]+$/
	if (re.test(val) || val == '') {
		return true;
	} else {
		return false;
	}
}

const isNumber = val => {
	var reg = /^[0-9]*$/;
	return reg.test(val);
}

const fomartDateToYMD = val => {
	if (val == '' || val == null) {
		return ''
	}
	return val.substring(0, 10).replace(new RegExp(/-/g), '/');
}

const getRandomColor = () => {
	var r = Math.round(Math.random() * 255);
	var g = Math.round(Math.random() * 255);
	var b = Math.round(Math.random() * 255);
	return 'rgb(' + r + ',' + g + ',' + b + ')';
}

let timer1 = null

function debounce(fn, t) {
	let delay = t || 500;
	return function() {
		let args = arguments;
		if (timer1) {
			clearTimeout(timer1);
		}
		timer1 = setTimeout(() => {
			fn.apply(this, args);
			timer1 = null;
		}, delay);
	}
}

function getOrderEndTime(stlist) {
	let end = stlist[stlist.length - 1];
	let sdate = new Date(end);
	sdate.setMinutes(sdate.getMinutes() + 30);
	let month = (sdate.getMonth() + 1) <= 9 ? "0" + (sdate.getMonth() + 1) : (sdate.getMonth() + 1);
	let date = sdate.getDate() <= 9 ? "0" + sdate.getDate() : sdate.getDate();
	let hours = sdate.getHours() <= 9 ? "0" + sdate.getHours() : sdate.getHours();
	let minutes = sdate.getMinutes() <= 9 ? "0" + sdate.getMinutes() : sdate.getMinutes();
	let nowEnd = sdate.getFullYear() + "/" + month + "/" + date + " " + hours + ":" + minutes;
	return nowEnd;
}

function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function formatTime(number, format) {

	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
	var returnArr = [];

	var date = new Date()
	if (number !== 0) {
		date = new Date(number);
	}
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));

	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));

	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}
	return format;
}
let timer2 = null;

function throttle(fn, t) {
	let last;
	let interval = t || 500;
	return function() {
		let args = arguments;
		let now = +new Date();
		if (last && now - last < interval) {
			clearTimeout(timer2);
			timer2 = setTimeout(() => {
				last = now;
				fn.apply(this, args);
			}, interval);
		} else {
			last = now;
			fn.apply(this, args);
		}
	}
};

function null2str(data) {
	for (let x in data) {
		if (data[x] === null) { // 如果是null 把直接内容转为 ''
			data[x] = '';
		} else {
			if (Array.isArray(data[x])) { // 是数组遍历数组 递归继续处理
				data[x] = data[x].map(z => {
					return null2str(z);
				});
			}
			if (typeof(data[x]) === 'object') { // 是json 递归继续处理
				data[x] = null2str(data[x])
			}
		}
	}
	return data;
}

// 处理多次点击
function noMultipleClicks(methods) {
	debounce(() => {
		methods();
	}, 700)()
}

function verifyPhoneNumber(value) {
	const regx = /^1[345789]\d{9}$/;
	return regx.test(value);
}

//获取几天后的时间
function getAddDateStr(AddDayCount) {
	var dd = new Date();
	dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
	var y = dd.getFullYear();
	var m = (dd.getMonth() + 1) <= 9 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1; //获取当前月份的日期
	var d = dd.getDate() <= 9 ? ("0" + dd.getDate()) : dd.getDate();
	return y + "-" + m + "-" + d;
}

function getWeekByDate(dayValue) {
	if (!dayValue) {
		return "";
	}
	var day = new Date(Date.parse(dayValue.replace(/-/g, '/')));
	var today = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
	return today[day.getDay()];
}

function formatDateToChinese(dateformatValue) {
	if (!dateformatValue) {
		return "";
	}
	let year = dateformatValue.substr(0, 4) + "年";
	let month = dateformatValue.substr(5, 2) + "月";
	let day = dateformatValue.substr(8, 2) + "日";
	return year + month + day;
}


function showShareMenu() {
	uni.showShareMenu({
		withShareTicket: true,
		menus: ['shareAppMessage', 'shareTimeline']
	});
}

function getDayName(d) {
	d = d.replace(/-/g, '/')
	var td = new Date();
	td = new Date(td.getFullYear(), td.getMonth(), td.getDate());
	var od = new Date(d);
	od = new Date(od.getFullYear(), od.getMonth(), od.getDate());
	var xc = (od - td) / 1000 / 60 / 60 / 24;
	if (xc < -2) {
		return -xc + "天前";
	} else if (xc < -1) {
		return "前天";
	} else if (xc < 0) {
		return "昨天";
	} else if (xc == 0) {
		return 1;
	} else if (xc < 2) {
		return "明天";
	} else if (xc < 3) {
		return "后天";
	} else {
		return xc + "天后";
	}
}
export {
	isLogin,
	toLogin,
	deepCopy,
	timeToDate,
	formatMoney,
	/* errorToBack, */
	successToShow,
	throttle,
	errorToShow,
	time2date,
	isPhoneNumber,
	isIdentity,
	isInArray,
	loadToShow,
	loadToHide,
	navigateTo,
	redirectTo,
	modelShow,
	builderUrlParams,
	isWeiXinBrowser,
	dateformat,
	getQueryString,
	timeToDateObj,
	moneySum,
	moneySub,
	shareParameterEncode,
	shareParameterDecode,
	formatDate,
	str2Date,
	isBlankString,
	isNumber,
	getRandomColor,
	debounce,
	getOrderEndTime,
	formatTime,
	null2str,
	noMultipleClicks,
	verifyPhoneNumber,
	getAddDateStr,
	getWeekByDate,
	formatDateToChinese,
	showShareMenu,
	getDayName,
	getmyDate
}